<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        clearable
        placeholder="标题"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
      />
      <el-select
        v-model="listQuery.category_id"
        clearable
        placeholder="所属栏目"
        style="width: 130px"
        class="filter-item"
        @change="handleFilter"
      >
        <!-- <el-option v-for="item in categoryOptions" :key="item.id" :value="item.id" :label="item.title" /> -->
        <tn-select-group
          :item="categoryOptions"
          label-key="label"
          value-key="id"
          :parent-click="false"
        />
      </el-select>
      <el-select
        v-model="listQuery.model_id"
        clearable
        placeholder="所属模型"
        style="width: 130px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option v-for="item in modelOptions" :key="item.id" :value="item.id" :label="item.cn_name + '(' + item.en_name + ')'" />
      </el-select>
      <el-button
        v-waves
        style="margin-left: 10px"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="handleAdd"
      >
        新增
      </el-button>
      <el-button
        class="filter-item"
        type="danger"
        icon="el-icon-delete"
        @click="handleDelete(0)"
      >
        批量删除
      </el-button>
    </div>

    <el-table
      ref="itemDataTable"
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;margin-top: 20px"
      @sort-change="tableSortChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        label="ID"
        prop="id"
        align="center"
        width="80"
      />
      <el-table-column label="标题" align="center">
        <template slot-scope="{ row: { titleWrapper }}">
          <span v-html="titleWrapper" />
        </template>
      </el-table-column>
      <el-table-column label="主图" width="80" align="center">
        <template slot-scope="{ row: { main_image: { prefix } }}">
          <img
            v-if="prefix === ''"
            style="width: 50px"
            src="@/assets/static/image/noImg.png"
          >
          <a v-else :href="prefix" target="_blank">
            <img
              :src="prefix"
              style="width: 50px"
            >
          </a>
        </template>
      </el-table-column>
      <el-table-column label="所属栏目" align="center" width="120">
        <template slot-scope="{ row: { category: { title } }}">
          <span>{{ title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属模型" align="center" width="120">
        <template slot-scope="{ row: { modelTable: { cn_name } }}">
          <span>{{ cn_name }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="查看数量"
        prop="view_count"
        sortable="custom"
        align="center"
        width="120"
      />
      <el-table-column
        label="点赞数量"
        prop="like_count"
        sortable="custom"
        align="center"
        width="120"
      />
      <el-table-column
        label="分享数量"
        prop="share_count"
        sortable="custom"
        align="center"
        width="120"
      />
      <el-table-column label="排序" align="center" width="120">
        <template slot-scope="{ row }">
          <el-input-number
            v-model="row.sort"
            controls-position="right"
            style="width: 100%"
            @change="handleContentSort($event, row.id)"
          />
        </template>
      </el-table-column>
      <el-table-column label="推荐" width="100" align="center">
        <template slot-scope="{ row }">
          <it-switch
            v-model="row.recomm"
            :active-value="1"
            :inactive-value="0"
            active-text="推荐"
            inactive-text="关闭"
            @change="handleContentStatus($event, row.id, 'recomm')"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="{ row }">
          <it-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            active-text="开启"
            inactive-text="停用"
            @change="handleContentStatus($event, row.id, 'status')"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" align="center" fixed="right">
        <template slot-scope="{ row: { id } }">
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(id)">编辑</el-button>
          <el-button size="mini" type="info" icon="el-icon-user" @click="handleShowUser(id)">用户</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="handleFilter"
    />

    <!-- 添加/编辑弹出框 -->
    <el-dialog
      :title="detailEditID !== 0 ? '编辑管理员信息' : '添加管理员信息'"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <content-detail :id="detailEditID" ref="contentDetail" @ended="handleSubmitEnd" />
    </el-dialog>

    <!-- 操作用户弹出框 -->
    <el-dialog
      title="查看操作用户"
      :visible.sync="dialogUserVisible"
      :close-on-click-modal="true"
      @close="closeUserDialog"
    >
      <content-user-detail :id="detailUserOperationID" ref="contentUserDetail" />
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import TnInnerTextSwitch from '@/components/TNInnerTextSwitch'
import TnSelectGroup from '@/components/TNSelectGroup'
import ContentDetail from './components/Detail'
import ContentUserDetail from './components/UserDetail'
import { getCategoryAllNode } from '@/api/category'
import { getModelTableAllName } from '@/api/model-table'
import { getContentList, updateContent, deleteContent } from '@/api/content'
import { wrapperKeyword } from '@/utils'

export default {
  name: 'ContentList',
  components: { Pagination, 'it-switch': TnInnerTextSwitch, TnSelectGroup, ContentDetail, ContentUserDetail },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      listLoading: false,
      total: 0,
      listQuery: {
        page: 1,
        limit: 20,
        title: '',
        category_id: '',
        model_id: ''
      },
      categoryOptions: [],
      modelOptions: [],
      list: [],
      detailEditID: 0,
      dialogFormVisible: false,
      detailUserOperationID: 0,
      dialogUserVisible: false
    }
  },
  watch: {
    list(val) {
      val.forEach(content => {
        content.titleWrapper = wrapperKeyword(this.listQuery['title'] || '', content.title)
      })
    }
  },
  mounted() {
    this.getOptionsData()
    this.getList()
  },
  methods: {
    handleFilter() {
      this.getList()
    },
    handleAdd() {
      this.detailEditID = 0
      this.dialogFormVisible = true
      this.$nextTick().then(() => {
        this.$refs.contentDetail.getAllNodeData()
      })
    },
    handleEdit(id) {
      this.detailEditID = id
      this.dialogFormVisible = true
      this.$nextTick().then(() => {
        this.$refs.contentDetail.getAllNodeData()
      })
    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除该数据，是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        // 判断是否为批量删除
        if (id === 0) {
          const _selection = this.$refs.itemDataTable.selection
          // console.log(_selection)
          if (_selection.length === 0) {
            this.$message({
              message: '请选择需要删除的数据',
              type: 'error'
            })
            return
          }
          _selection.forEach((value, index) => {
            ids.push(value.id)
          })
        } else {
          ids.push(id)
        }

        // console.log(ids)

        deleteContent(ids).then(response => {
          this.$message({
            message: response.msg,
            type: 'success'
          })
          this.getList()
        })
      }).catch(() => {})
    },
    handleContentSort(value, id) {
      // console.log(id, value)
      updateContent({
        id,
        field: 'sort',
        value
      }).then(response => {
        this.$message({
          message: response.msg,
          type: 'success',
          duration: 2000
        })
      })
    },
    handleContentStatus(value, id, field) {
      updateContent({
        id,
        field,
        value
      }).then(response => {
        this.$message({
          message: response.msg,
          type: 'success',
          duration: 2000
        })
      })
    },
    closeDialog() {
      this.$refs.contentDetail.toDefault()
      this.detailEditID = 0
    },
    handleSubmitEnd() {
      this.dialogFormVisible = false
      this.getList()
    },
    handleShowUser(id) {
      this.detailUserOperationID = id
      this.dialogUserVisible = true
      this.$nextTick().then(() => {
        this.$refs.contentUserDetail.getUserList()
      })
    },
    closeUserDialog() {
      this.detailUserOperationID = 0
      this.$refs.contentUserDetail.toDefault()
    },
    getOptionsData() {
      getCategoryAllNode().then(response => {
        const { data } = response
        this.categoryOptions = data
      })
      getModelTableAllName().then(response => {
        const { data } = response
        this.modelOptions = data
      })
    },
    tableSortChange(data) {
      const { prop, order } = data
      // console.log(prop, order, data)
      this.listQuery.sort_prop = prop
      this.listQuery.sort_order = order
      this.getList()
    },
    getList() {
      this.listLoading = true
      getContentList(this.listQuery).then(response => {
        const {
          total,
          data
        } = response
        this.total = total
        this.list = data
        this.listLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>

